<template>
  <n-drawer
    v-model:show="modelValue.toEdit"
    :width="600"
    :height="800"
    :placement="'bottom'"
  >
    <n-drawer-content
      :title="toADDFlag ? '添加' : '修改'"
      closable
      :mask-closable="false"
    >
      <n-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
        :size="'medium'"
        label-placement="left"
        label-width="auto"
        require-mark-placement="right-hanging"
        :style="{ maxWidth: '500px' }"
      >
        <n-form-item
          label="名字"
          path="name"
        >
          <n-input
            v-model:value="formValue.name"
            placeholder="输入名字"
          />
        </n-form-item>
        <n-form-item
          label="状态"
          path="state"
        >
          <n-select
            v-model:value="formValue.state"
            :options="StateMoal.getStateMap4NewStage(toADDFlag)"
          />
        </n-form-item>
        <n-form-item
          label="所属领域"
          path="fatherId"
        >
          <n-select
            v-model:value="formValue.fatherId"
            :options="fieldTree.getFieldSelectOptions()"
          />
        </n-form-item>
        <!--        {{formValue}} {{formRef}}-->
        <n-form-item>
          <n-button
            attr-type="button"
            @click="handleValidateClick"
          >
            {{ toADDFlag ? "添加" : "修改" }}
          </n-button>
        </n-form-item>
      </n-form>
      <markdown v-model="text"></markdown>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup generic="T extends object & { toEdit: boolean,toDelete:boolean,toDealRowId: number|undefined}">
//  <n-time-picker v-model:value="formValue.startTime"/>
// <n-time-picker :default-value="1183135260000" />
// <n-time-picker v-model:value="formValue.endTime" />
import markdown from "@/components/common/markDown.vue";
import { RemoveMethods } from "@/types/remove-methods";
import { FinishStage, FinishStageList } from "@model/StageFinish";
import { StateMoal } from "@model/StateMoal";
import { TaskData } from "@model/TaskList";
import { TaskLogData } from "@model/TaskLogMap";
import { StageData, StageList, TaskIdsModal, TimeLogModel } from "@model/stage";
import { SurfaceSetting } from "@model/surfaceSetting";
import UseCacheFinishStageMap from "@pinias/UseCacheFinishStageMap";
import UseCacheIdStatMap from "@pinias/UseCacheIdStatMap";
import UseCacheTaskLog from "@pinias/UseCacheTaskLog";
import UseFieldTree from "@pinias/UseFieldTree";
import UseStage from "@pinias/UseStage";
import UseSurfaceSetting from "@pinias/UseSurfaceSetting";
import UseTask from "@pinias/UseTask";
import pinia from "@pinias/pinia";
import { DateTimeStr } from "@utils/DateUtils";
import { NForm, NFormItem, NInput, NDrawer, NDrawerContent, NButton, FormInst, useMessage } from "naive-ui";
import { ref, computed, watch, onMounted, reactive } from "vue";

// 全局数据
const { getSurfaceSetting } = UseSurfaceSetting(pinia);
const surfaceSetting: SurfaceSetting = getSurfaceSetting();
const { getStageList } = UseStage(pinia);
const stageList: StageList = getStageList();
const { getFieldTree } = UseFieldTree(pinia);
const fieldTree = getFieldTree();
const { getCacheFinishStageMap } = UseCacheFinishStageMap(pinia);
const cacheFinishStageMap = getCacheFinishStageMap();
const { getCacheIdStatMap } = UseCacheIdStatMap(pinia);
const cacheIdStatMap = getCacheIdStatMap();
const { getCacheTaskLogMap } = UseCacheTaskLog(pinia);
const cacheTaskLogMap = getCacheTaskLogMap();
const { getTaskList } = UseTask(pinia);
const taskList = getTaskList();
// 父组件数据
const props = defineProps<{ modelValue: T }>();
const emit = defineEmits(["update:modelValue"]);
const modelValue = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val),
});

// 页面数据
const toADDFlag = computed(() => {
  return typeof modelValue.value.toDealRowId == "undefined";
});
const rules = {
  name: {
    required: true,
    message: "请输入名字",
    trigger: ["input"],
  },
  state: {
    required: true,
    message: "请选择状态",
    trigger: ["change"],
  },
  // fatherId: {
  //   required: true,
  //   message: "请选择领域",
  //   trigger: ["change"],
  // },
};
const formRef = ref<FormInst | null>(null);
class RowData {
  id: number;
  name: string;
  state: string;
  fatherId: number;
  markDownFile: string;

  constructor(data: RemoveMethods<RowData>) {
    Object.assign(this, data);
  }
  static getNullModel() {
    return new RowData({
      id: surfaceSetting.maxId,
      name: "",
      state: "stopping",
      fatherId: surfaceSetting.getShowField(),
      markDownFile: "",
    });
  }
}
const getNewFormValue = async () => {
  // console.log('getNewFormValue',toDealField);
  const nullModel = RowData.getNullModel();
  if (toADDFlag.value) {
    return nullModel;
  } else {
    if (surfaceSetting.StageState === "finished") {
      const showField = surfaceSetting.getShowField();
      if (showField !== undefined && modelValue.value.toDealRowId !== undefined) {
        const finishStageList = await cacheFinishStageMap.getFinishStageList(showField);
        const oldData = FinishStageList.getFinishStage(finishStageList, modelValue.value.toDealRowId);
        if (oldData !== undefined) {
          return new RowData({
            id: modelValue.value.toDealRowId,
            name: oldData.name,
            state: surfaceSetting.StageState,
            fatherId: oldData.fatherId,
            markDownFile: oldData.markDownFile,
          });
        }
      }
    } else {
      const oldData = stageList.getStageDataById(modelValue.value.toDealRowId);
      if (oldData === undefined || modelValue.value.toDealRowId === undefined) return nullModel;
      else
        return new RowData({
          id: modelValue.value.toDealRowId,
          name: oldData.name,
          state: surfaceSetting.StageState,
          fatherId: oldData.fatherId,
          markDownFile: oldData.markDownFile,
        });
    }
  }
  return nullModel;
};
const formValue = ref(RowData.getNullModel());
const oldValue = ref(RowData.getNullModel());
// console.log('formValue',formValue.value);
watch(modelValue.value, async () => {
  // console.log('formValue',formValue);
  formValue.value = await getNewFormValue();
  oldValue.value = await getNewFormValue();
  text.text = formValue.value.markDownFile;
  // console.log('formValue2',formValue);
});
onMounted(async () => {
  formValue.value = await getNewFormValue();
  oldValue.value = await getNewFormValue();
  text.text = formValue.value.markDownFile;
});
// markDown编辑器
const text = reactive({ text: formValue.value.markDownFile });

// 添加逻辑
const message = useMessage();
const addNew = async () => {
  const tosave = formValue.value;
  if (fieldTree.getFieldDataById(tosave.fatherId) === undefined) {
    message.error("所属领域不存在");
    return;
  }
  // console.log("tosave", tosave);
  // 添加情况
  if (toADDFlag.value) {
    const fieldData = fieldTree.getFieldDataById(tosave.fatherId);
    if (fieldData !== undefined && tosave.id !== undefined) {
      const stageIds = StateMoal.getStateId(fieldData.stageIds, tosave.state);
      // console.log(tosave.state, stageIds);
      stageIds.push(tosave.id);
      stageList.addStageData(
        new StageData(tosave.id, tosave.name, StateMoal.getLastStartTime(tosave.state), tosave.fatherId),
      );
      surfaceSetting.maxId++;
    }
  } else {
    // 编辑情况 //
    // 已结束的阶段编辑
    if (oldValue.value.state === "finished") {
      if (tosave.state !== "finished") {
        message.error("已结束的阶段不可修改状态");
        return;
      }
      // 更新文件数据
      const changeKey = new Set<string>();
      const finishStageList = await cacheFinishStageMap.getFinishStageList(oldValue.value.fatherId);
      const oldData = FinishStageList.getFinishStage(finishStageList, tosave.id);
      if (
        oldData !== undefined &&
        (oldData.name !== tosave.name || oldData.fatherId !== tosave.fatherId || oldData.markDownFile != text.text)
      ) {
        oldData.name = tosave.name;
        oldData.fatherId = tosave.fatherId;
        oldData.markDownFile = text.text;
        changeKey.add(oldValue.value.fatherId.toString());
      }
      // 更换阶段的领域，交换文件中的数据
      if (oldValue.value.fatherId !== tosave.fatherId && oldData !== undefined) {
        // 存任务的fatherId
        const taskIds = FinishStage.getTaskDataList(oldData, 3).map(value => value.id);
        await cacheIdStatMap.changeTaskFatherId(oldData.id, taskIds); // idStat更换每个task的fatherId
        // 存领域下的已结束阶段数据
        const newFinishStageList = await cacheFinishStageMap.getFinishStageListCreate(tosave.fatherId);
        FinishStageList.addFinishStage(newFinishStageList, oldData);
        // console.log("newFinishStageList",newFinishStageList)
        const oldFinishStageList = await cacheFinishStageMap.getFinishStageList(oldValue.value.fatherId);
        FinishStageList.deleteFinishStage(oldFinishStageList, tosave.id);
        // console.log("newFinishStageList",oldFinishStageList)
        changeKey.add(oldValue.value.fatherId.toString());
        changeKey.add(tosave.fatherId.toString());
        const stageData = stageList.getStageDataById(tosave.id);
        if (stageData !== undefined) {
          stageData.fatherId = tosave.fatherId;
        }
      }
      if (changeKey.size > 0) cacheFinishStageMap.changeKeys = [...changeKey];
      // console.log("newFinishStageList",cacheFinishStageMap.changeKeys)
    } else {
      // 未结束的阶段编辑
      const fieldData = fieldTree.getFieldDataById(tosave.fatherId);
      const oldFieldData = fieldTree.getFieldDataById(oldValue.value.fatherId);
      const data = stageList.getStageDataById(tosave.id);
      if (data !== undefined) {
        // console.log(data.task,TaskIdsModal.checkIsAllFinish(data.task),TaskIdsModal.hasTask(data.task),"++++++++++")
        if (
          tosave.state !== oldValue.value.state &&
          tosave.state === "finished" &&
          (!TaskIdsModal.checkIsAllFinish(data.task) || !TaskIdsModal.hasTask(data.task))
        ) {
          message.error("存在未完成的任务，或者还未建立任务");
          return;
        }
        if (tosave.state !== oldValue.value.state && tosave.fatherId !== oldValue.value.fatherId) {
          message.error("不可修改状态时，再修改所属领域");
          return;
        }
        if (tosave.state === "finished") {
          // console.log(
          //   "++++++++++++++++++++",
          //   data,
          //   new Date().getTime() - data.lastStartTime,
          //   surfaceSetting.StageLastStartTimeInterval,
          // );
          if (data.lastStartTime <= 0) {
            message.error("阶段未进行中过，不可结束");
            return;
          } else if (
            data.startTime.length <= 0 &&
            new Date().getTime() - data.lastStartTime <= surfaceSetting.StageLastStartTimeInterval
          ) {
            message.error("阶段进行时间未超过一天，不可结束");
            return;
          }
        }
        // 数据处理
        data.name = tosave.name;
        data.fatherId = tosave.fatherId;
        data.markDownFile = text.text;
        // console.log(data,"++++++++++++++")
        // 切换阶段状态时，状态处理
        if (tosave.state !== oldValue.value.state) {
          if (tosave.state === "onGonging") {
            data.lastStartTime = StateMoal.getLastStartTime(tosave.state);
          }
          if (tosave.state === "stopping" || tosave.state === "finished") {
            if (new Date().getTime() - data.lastStartTime > surfaceSetting.StageLastStartTimeInterval) {
              data.startTime.push(new TimeLogModel(data.lastStartTime, new Date().getTime()));
            }
          }
          if (oldFieldData !== undefined) StateMoal.deleteId(oldFieldData.stageIds, tosave.id, oldValue.value.state);
          if (fieldData !== undefined) StateMoal.addId(fieldData.stageIds, tosave.id, tosave.state);
          // 已结束完成状态
          if (tosave.state === "finished") {
            data.finished = true;
            // 找好当前stage以及task信息,放入已结束中
            const taskBasedData = new Array<TaskData>();
            const saveFatherIds = new Array<number>();
            let taskIdList = [...StateMoal.getStateId(data.task.TaskBased, tosave.state)];
            for (let i = 0; i < taskIdList.length; i++) {
              const id = taskIdList[i];
              saveFatherIds.push(id);
              const taskData = taskList.getTaskDataById(id);
              if (taskData !== undefined) {
                taskBasedData.push(taskData);
                taskList.deleteTaskDataById(id);
                StateMoal.deleteId(data.task.TaskBased, id, tosave.state);
              }
            }
            const clockBasedData = new Array<TaskData>();
            taskIdList = [...StateMoal.getStateId(data.task.ClockBased, tosave.state)];
            for (let i = 0; i < taskIdList.length; i++) {
              const id = taskIdList[i];
              saveFatherIds.push(id);
              const taskData = taskList.getTaskDataById(id);
              if (taskData !== undefined) {
                clockBasedData.push(taskData);
                taskList.deleteTaskDataById(id);
                StateMoal.deleteId(data.task.ClockBased, id, tosave.state);
              }
            }
            // console.log("data",data.fatherId,tosave,data)
            // 存入文件中
            await cacheIdStatMap.changeTaskFatherId(data.id, saveFatherIds);
            const finishStageList = await cacheFinishStageMap.getFinishStageListCreate(data.fatherId);
            const finishStage = new FinishStage(
              data.id,
              data.name,
              data.lastStartTime,
              data.fatherId,
              data.startTime,
              data.markDownFile,
              taskBasedData,
              clockBasedData,
            );
            FinishStageList.addFinishStage(finishStageList, finishStage);
            // console.log("finishStageList",finishStageList,finishStage)
            cacheFinishStageMap.changeKeys.push(finishStageList.id);
            // 删除领域的阶段信息
            if (fieldData !== undefined) StateMoal.deleteId(fieldData.stageIds, tosave.id, tosave.state);
          }
        }

        // 更换阶段领域时，领域处理
        if (oldValue.value.fatherId !== tosave.fatherId) {
          if (oldFieldData !== undefined) StateMoal.deleteId(oldFieldData.stageIds, tosave.id, oldValue.value.state);
          if (fieldData !== undefined) StateMoal.addId(fieldData.stageIds, tosave.id, tosave.state);
        }
      }
    }
    // 切换领域时，更新对应领域的统计情况：
    if (oldValue.value.fatherId !== tosave.fatherId) {
      // 统计情况：找到taskId，加入其中；然后找到父id，加入其中
      const stageIdStat = await cacheIdStatMap.getIdStatNotCreate(tosave.id);
      // console.log("stageIdStat",stageIdStat)
      const taskLogDatas = new Array<TaskLogData>();
      if (stageIdStat !== undefined) {
        for (let value of stageIdStat.everyDayLogMap.values()) {
          for (let i = 0; i < value.length; i++) {
            const valueKey = value[i];
            const timeStamp = DateTimeStr.getTimeStamp(valueKey);
            // console.log("timeStamp",timeStamp,valueKey,value)
            if (timeStamp > 0) {
              const taskLogMap = await cacheTaskLogMap.getTaskLogMap(timeStamp);
              const taskLogData = taskLogMap.taskLogMap.get(valueKey);
              // console.log("taskLogMap",taskLogMap,taskLogData)
              if (taskLogData !== undefined) taskLogDatas.push(taskLogData);
            }
          }
        }
      }
      // console.log("taskLogDatas",taskLogDatas)
      if (taskLogDatas.length > 0) {
        await cacheIdStatMap.changeTaskLogData4Stat(taskLogDatas, [oldValue.value.fatherId], taskLogDatas, [
          tosave.fatherId,
        ]);
      }
    }
  }
  // formValue = getNewFormValue();
  surfaceSetting.StageListKey = new Date().getTime();
  modelValue.value.toEdit = false;
};
const handleValidateClick = (e: MouseEvent) => {
  // console.log('toDealRow',toDealRow);
  e.preventDefault();
  formRef.value?.validate(errors => {
    if (!errors) {
      // message.success("Valid");
      addNew();
    } else {
      console.log(errors);
      // message.error("Invalid");
    }
  });
};
</script>

<style scoped></style>
